package com.cymal.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;

public class JacksonUtils {
    private static final ObjectMapper om = new ObjectMapper();

    public static String toJson(Object obj) {
        if (obj == null) {
            return null;
        } else {
            try {
                return om.writeValueAsString(obj);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static <T> T formJson(String json, Class<T> cls) {
        if (json != null && !json.trim().isEmpty()) {
            try {
               return om.readValue(json, cls);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }

    public static JsonNode readTree(String jsonStr) {
        if (jsonStr == null) {
            return null;
        } else {
            try {
                return om.readTree(jsonStr);
            } catch (IOException var2) {
                throw new RuntimeException(var2);
            }
        }
    }

    public static byte[] toBytes(Object obj) {
        try {
            return obj != null ? om.writeValueAsBytes(obj) : null;
        } catch (Exception var2) {
            throw new RuntimeException(var2);
        }
    }

    public static <T> T fromBytes(byte[] bs, Class<T> clazz) {
        try {
            return bs != null ? om.readValue(bs, clazz) : null;
        } catch (Exception var3) {
            throw new RuntimeException(var3);
        }
    }


    static {
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        om.enable(SerializationFeature.INDENT_OUTPUT);
        om.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }



}
